﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml;
using WeBlog.Interfaces;
using WeBlog.Models;
using WeBlog.Repositories;
using WeBlog.Services;

namespace WeBlog.ActionResults {
    
    public class SitemapActionResult : ActionResult
    {
        private readonly IEnumerable<Post> _posts;
        private readonly IEnumerable<Category> _categories;
        private readonly SiteConfiguration _configuration;

        public SitemapActionResult( IUnitOfWork unitOfWork )
        {
            _configuration = SiteManager.CurrentConfiguration;

            var postRepository = new PostRepository(unitOfWork);
            _posts = postRepository.PublishedPosts();
            var categoryRepository = new CategoryRepository(unitOfWork);
            _categories = categoryRepository.FindUsedCategories();
        }
 
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "application/xml";

            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output)) {
                writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
                writer.WriteStartElement("url");
                writer.WriteElementString("loc", SiteManager.GetBaseUrl());
                writer.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd"));
                writer.WriteElementString("changefreq", "daily");
                writer.WriteElementString("priority", "1.0");
                writer.WriteEndElement();

                foreach (Post post in _posts) {
                    writer.WriteStartElement("url");
                    writer.WriteElementString("loc", post.GetPermalink().ToString());
                    writer.WriteElementString("lastmod", post.PublishDate.Value.ToString("yyyy-MM-dd"));
                    writer.WriteElementString("changefreq", "daily");
                    writer.WriteElementString("priority", "0.5");
                    writer.WriteEndElement();
                }

                foreach (Category category in _categories) {
                    writer.WriteStartElement("url");
                    writer.WriteElementString("loc", category.GetPermalink().ToString() );
                    writer.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd"));
                    writer.WriteElementString("changefreq", "daily");
                    writer.WriteElementString("priority", "0.5");
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.Flush();
                writer.Close();
            }
        }
    }
}